package com.basiclib.utils

import android.content.ActivityNotFoundException
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.text.TextUtils
import android.widget.Toast


object GoToScoreUtils {

    /**
     * 第一种方法
     * @param context
     * @param packageName
     */
    @JvmStatic
    fun goToMarket(context: Context, packageName: String) {
        try {
            val uri = Uri.parse("market://details?id=$packageName")
            val goToMarket = Intent(Intent.ACTION_VIEW, uri)
            goToMarket.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            context.startActivity(goToMarket)
        } catch (e: ActivityNotFoundException) {
            e.printStackTrace()
            Toast.makeText(context, "您的手机没有安装Android应用市场", Toast.LENGTH_SHORT).show()
            when (Build.BRAND) {
                "samsung" -> gotoSamsungMarket(context, packageName)
            }
        }

    }

    private fun gotoSamsungMarket(context: Context, packageName: String) {
        val uri = Uri.parse("http://www.samsungapps.com/appquery/appDetail.as?appId=$packageName")
        val intent = Intent()
        intent.setClassName("com.sec.android.app.samsungapps", "com.sec.android.app.samsungapps.Main")
        intent.data = uri
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        try {
            context.startActivity(intent)
        } catch (e: ActivityNotFoundException) {
            e.printStackTrace()
        }
    }

    /**
     * 第二种方法
     * 直接跳转到应用宝
     * @param context
     * @param packageName
     */
    @JvmStatic
    fun goToMarketQQ(context: Context, packageName: String) {
        try {
            val uri = Uri.parse("market://details?id=$packageName")
            val goToMarket = Intent(Intent.ACTION_VIEW, uri)
            goToMarket.setClassName("com.tencent.android.qqdownloader", "com.tencent.pangu.link.LinkProxyActivity")
            context.startActivity(goToMarket)
        } catch (e: ActivityNotFoundException) {
            e.printStackTrace()
            Toast.makeText(context, "您的手机没有安装应用宝", Toast.LENGTH_SHORT).show()
        }

    }


    /**
     * 第三种方法
     * 首先先获取手机上已经安装的应用市场
     * 获取已安装应用商店的包名列表
     * 获取有在AndroidManifest 里面注册<category android:name="android.intent.category.APP_MARKET"></category>的app
     * @param context
     * @return
     */
    @JvmStatic
    fun getInstallAppMarkets(context: Context?): MutableList<String> {
        //默认的应用市场列表，有些应用市场没有设置APP_MARKET通过隐式搜索不到
        val pkgList = mutableListOf<String>()
        //将我们上传的应用市场都传上去
        pkgList.add("com.xiaomi.market")                       //小米应用商店
        pkgList.add("com.lenovo.leos.appstore")                //联想应用商店
        pkgList.add("com.oppo.market")                         //OPPO应用商店
        pkgList.add("com.tencent.android.qqdownloader")        //腾讯应用宝
        pkgList.add("com.qihoo.appstore")                      //360手机助手
        pkgList.add("com.baidu.appsearch")                     //百度手机助手
        pkgList.add("com.huawei.appmarket")                    //华为应用商店
        pkgList.add("com.wandoujia.phoenix2")                  //豌豆荚
        pkgList.add("com.hiapk.marketpho")                     //安智应用商店
        pkgList.add("com.sec.android.app.samsungapps")                     //三星应用商店
        val pkgs = mutableListOf<String>()
        if (context == null)
            return pkgs
        val intent = Intent()
        intent.action = "android.intent.action.MAIN"
        intent.addCategory("android.intent.category.APP_MARKET")
        val pm = context.packageManager
        val info = pm.queryIntentActivities(intent, 0)
        if (info == null || info.size == 0)
            return pkgs
        val size = info.size
        for (i in 0 until size) {
            var pkgName = ""
            try {
                val activityInfo = info[i].activityInfo
                pkgName = activityInfo.packageName
            } catch (e: Exception) {
                e.printStackTrace()
            }

            if (!TextUtils.isEmpty(pkgName))
                pkgs.add(pkgName)
        }
        //取两个list并集,去除重复
        pkgList.removeAll(pkgs)
        pkgs.addAll(pkgList)
        return pkgs
    }


    /**
     * 获取已安装应用商店的包名列表
     * @param context       context
     * @return
     */
    fun queryInstalledMarketPkgs(context: Context?): MutableList<String> {
        val pkgs = mutableListOf<String>()
        if (context == null)
            return pkgs
        val intent = Intent()
        intent.action = "android.intent.action.MAIN"
        intent.addCategory("android.intent.category.APP_MARKET")
        val pm = context.packageManager
        val infos = pm.queryIntentActivities(intent, 0)
        if (infos == null || infos.size == 0)
            return pkgs
        val size = infos.size
        for (i in 0 until size) {
            var pkgName = ""
            try {
                val activityInfo = infos[i].activityInfo
                pkgName = activityInfo.packageName
            } catch (e: Exception) {
                e.printStackTrace()
            }

            if (!TextUtils.isEmpty(pkgName))
                pkgs.add(pkgName)
        }
        return pkgs
    }

    /**
     * 过滤出已经安装的包名集合
     * @param context
     * @param pkgs 待过滤包名集合
     * @return 已安装的包名集合
     */
    fun filterInstalledPkgs(context: Context?, pkgs: MutableList<String>?): MutableList<String> {
        val empty = mutableListOf<String>()
        if (context == null || pkgs.isNullOrEmpty())
            return empty
        val pm = context!!.packageManager
        val installedPkgs = pm.getInstalledPackages(0)
        val li = installedPkgs.size
        val lj = pkgs.size
        for (j in 0 until lj) {
            for (i in 0 until li) {
                var installPkg = ""
                val checkPkg = pkgs[j]
                try {
                    installPkg = installedPkgs.get(i).applicationInfo.packageName
                } catch (e: Exception) {
                    e.printStackTrace()
                }

                if (TextUtils.isEmpty(installPkg))
                    continue
                if (installPkg == checkPkg) {
                    empty.add(installPkg)
                    break
                }
            }
        }
        return empty
    }


    /**
     * 跳转到应用市场app详情界面
     * @param appPkg    App的包名
     * @param marketPkg 应用市场包名
     */
    @JvmStatic
    fun launchAppDetail(context: Context, appPkg: String, marketPkg: String) {
        try {
            if (TextUtils.isEmpty(appPkg))
                return
            val uri = Uri.parse("market://details?id=$appPkg")
            val intent = Intent(Intent.ACTION_VIEW, uri)
            if (!TextUtils.isEmpty(marketPkg)) {
                intent.setPackage(marketPkg)
            }
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            context.startActivity(intent)
        } catch (e: Exception) {
            e.printStackTrace()
        }

    }

}